package yns.springboot.frontend.sample.service.impl;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import yns.springboot.frontend.sample.dto.WebSampleInfoDto;
import yns.springboot.frontend.sample.service.LayuiSampleService;

@Service
public class LayuiSampleServiceImpl implements LayuiSampleService {

	private static final String NEWS_CNBLOGS_URL = "https://news.cnblogs.com/";

	@Override
	public List<WebSampleInfoDto> getSampleInfo() throws IOException {
		Document doc = Jsoup.connect(NEWS_CNBLOGS_URL).header("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36")
				.get();

		System.out.println(doc.title());
		doc.setBaseUri(NEWS_CNBLOGS_URL);

		List<WebSampleInfoDto> listWebSampleInfoDtos = new ArrayList<>();

		Elements news_List_Div = doc.select("#news_list");
		//System.out.println(news_List_Div);
		
		Elements news_List_Elements = news_List_Div.select(".news_block > .content > h2 > a");
		System.out.println(news_List_Elements);
		System.out.println(news_List_Elements.size());

		String url;
		String name;

		for (Element element : news_List_Elements) {
			Element element_A = element.getElementsByTag("a").first();
			url = element_A.absUrl("href");
			name = element_A.text();

			if ("".equals(url) && "".equals(name)) {
				continue;
			}


			WebSampleInfoDto webSampleInfoDto = new WebSampleInfoDto();
			webSampleInfoDto.setName(name);
			webSampleInfoDto.setHref(url);
			webSampleInfoDto.setDate(LocalDate.now().toString());
			webSampleInfoDto.setLocalDateTime(LocalDateTime.now());
			listWebSampleInfoDtos.add(webSampleInfoDto);
		}

		return listWebSampleInfoDtos;
	}

	public static void main(String[] args) throws IOException {
		Document doc = Jsoup.connect(NEWS_CNBLOGS_URL).header("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36")
				.get();

		System.out.println(doc.title());
		doc.setBaseUri(NEWS_CNBLOGS_URL);
		
		Elements news_List_Div = doc.select("#news_list");
		//System.out.println(news_List_Div);
		
		Elements news_List_Elements = news_List_Div.select(".news_block > .content > h2 > a");
		System.out.println(news_List_Elements);
		System.out.println(news_List_Elements.size());
		
		String url;
		String name;
		
		for (Element element : news_List_Elements) {
			Element element_A = element.getElementsByTag("a").first();
			url = element_A.absUrl("href");
			name = element_A.text();

			if ("".equals(url) && "".equals(name)) {
				continue;
			}
			
			System.out.println(name + " " + url);
		}

	}

}
